package com.ruoyi.dataserver.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.BigExcelWriter;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.dataserver.api.dto.StatisticResultDTO;
import lombok.SneakyThrows;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @ProjectName intelligent-city
 * @Package com.lab.dataserver.utils
 * @ClassName ExcelExportUtils
 * @Description Excel文件导出
 * @Company Lab
 * @Author songhw
 * @Date 2020/7/21 0021 9:52
 * @UpdateUser
 * @UpdateDate
 * @UpdateRemark
 * @Version 1.0.0
 */
public class ExcelExportUtils {

    public void lengthUtil(String deviceTemplate, StatisticResultDTO statisticResultDTO, HttpServletResponse response) throws IOException {
            List<String> list = new ArrayList();
            list.add("管线类型");
            list.add("分组字段");
            list.add("长度(米)");
            export(statisticResultDTO,response,deviceTemplate,list);
    }
    public void countUtil(String deviceTemplate,StatisticResultDTO statisticResultDTO,HttpServletResponse response) throws IOException {
            List<String> list = new ArrayList();
            list.add("管线类型");
            list.add("分组字段");
            list.add("个数");
            export(statisticResultDTO,response,deviceTemplate,list);
    }

    public void export(StatisticResultDTO statisticResultDTO, HttpServletResponse response,String deviceTemplate,List list) throws IOException {

        List statisticsData = statisticResultDTO.getStatisticsData();

        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式
        String format = df.format(new Date());// new Date()为获取当前系统时间
        String destFilePath = deviceTemplate+"/"+format+".xlsx";

        BigExcelWriter writer = ExcelUtil.getBigWriter(destFilePath);

        ArrayList<Object> home = CollUtil.newArrayList(list.get(0),list.get(1),list.get(2));
        List homeCollection = new ArrayList();
        homeCollection.add(home);
        writer.write(homeCollection, true);
        ArrayList<String> rows = null;
        for (int i = 0; i < statisticsData.size(); i++) {
            List<String> row =null;
            List collection = new ArrayList();
            JSONObject jsonObject = JSON.parseObject(JSONObject.toJSONString(statisticsData.get(i)));
            if(list.get(2).equals("个数")){
                row = CollUtil.newArrayList(jsonObject.get("layerName").toString(),jsonObject.get("fieldName").toString(),jsonObject.get("count").toString());
            }else if(list.get(2).equals("长度(米)")){
                DecimalFormat formatNumber = new DecimalFormat("0.00");
                row = CollUtil.newArrayList(jsonObject.get("layerName").toString(),jsonObject.get("fieldName").toString(),formatNumber.format(new BigDecimal(jsonObject.get("length").toString())));
            }
            collection.add(row);
            rows = CollUtil.newArrayList(collection);
            writer.write(rows, true);

            JSONArray jsonArray1 = JSONArray.parseArray(JSONObject.toJSONString(jsonObject.get("detailList")));
            for (int j = 0; j < jsonArray1.size(); j++) {
                List<String> row1 =null;
                List collection1 = new ArrayList();
                JSONObject jsonObject1 = JSON.parseObject(JSONObject.toJSONString(jsonArray1.get(j)));
                if(list.get(2).equals("个数")){
                    row1 = CollUtil.newArrayList("",jsonObject1.get("fieldName").toString(),jsonObject1.get("count").toString());
                }else if(list.get(2).equals("长度(米)")){
                    DecimalFormat formatNumber = new DecimalFormat("0.00");
                    row1 = CollUtil.newArrayList("",jsonObject1.get("fieldName").toString(),formatNumber.format(new BigDecimal(jsonObject1.get("length").toString())));
                }
                collection1.add(row1);
                rows = CollUtil.newArrayList(collection1);
                writer.write(rows, true);
            }
        }
        // 关闭writer，释放内存
        writer.close();
        if(destFilePath != null){
            downFile(destFilePath,response);
        }
        //this.delFile(destFilePath);
    }

    /**
     * @Title downFile  下载文件
     * @Description
     * @param filePath :
     * @param response :
     * @return void
     * @author zhangzhy
     * @date 2020/5/7 16:13
     */
    //@SneakyThrows
    public static void downFile(String filePath, HttpServletResponse response) throws IOException {
        if(StrUtil.isNotBlank(filePath)){
            File file = new File(filePath);
            if(file.exists()) {
                BufferedInputStream br = null;
                OutputStream out = null;
                // 取得文件名。
               try {
                   String filename = file.getName();
                   br = new BufferedInputStream(new FileInputStream(file));
                   byte[] buf = new byte[1024];
                   int len = 0;
                   response.reset();
                   response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename.trim(),"UTF-8") );
                   response.setHeader("Content-Length", ""+file.length());
                   response.setCharacterEncoding("UTF-8");
                   out = response.getOutputStream();
                   while ((len = br.read(buf)) > 0)
                       out.write(buf, 0, len);

               }catch (Exception e){
                   e.printStackTrace();
               }finally {
                   br.close();
                   out.close();
               }
            }
        }
    }
    /**
     * 删除本地临时文件
     */
    //删除文件
    public static void delFile(String filePathAndName) {
        try {
            String filePath = filePathAndName;
            filePath = filePath.toString();
            File myDelFile = new File(filePath);
            myDelFile.delete();
        } catch (Exception e) {
            System.out.println("删除文件操作出错");
            e.printStackTrace();
        }
    }

}
